package com.bsh.service.impl;

import com.bsh.entity.Bo.User;
import com.bsh.mapper.UserMapper;
import com.bsh.service.UserService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ExecutorService;


@Service
public class UserServiceImpl implements UserService {

    /*private final ExecutorService executorService;
    private final SqlSessionFactory sqlSessionFactory;

    @Autowired
    public UserServiceImpl(ExecutorService executorService, SqlSessionFactory sqlSessionFactory) {
        this.executorService = executorService;
        this.sqlSessionFactory = sqlSessionFactory;
    }*/

    @Resource
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUserData() {

        /*for (int i = 0; i < 100; i++) {
            final int threadId = i;
            executorService.submit(() -> {
                try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
                    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);


                    sqlSession.commit();
                }
            });
        }

        // 关闭线程池
        executorService.shutdown();*/

        for (int j = 0; j < 10000000; j++) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // 截取前11位作为随机数
            String randomNum = uuid.substring(0, 11);
            // 创建随机数生成器
            Random random = new Random();

            // 生成1或2的随机数
            int randomNumber = random.nextInt(2) + 1;
            User user = new User();
            user.setUserName("cdd" + j);
            user.setPhone(randomNum);
            user.setSex(randomNumber);
            user.setPassword(uuid);
            user.setBalance((double) j);
            user.setNote("这是第" + j + "条");
            user.setCreateDate(new Date());
            userMapper.insert(user);

        }



    }



    @Override
    public void updateData(String userId, String password) {
        /*executorService.submit(() -> {
            try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

                // 同时操作同一条数据库数据
                User user = userMapper.selectById(userId);
                user.setPassword(password);
                userMapper.updateById(user);

                sqlSession.commit();
            }
        });*/
    }
}
